<template>
  <div class="content">
    <div ref="parentRef" class="con">
      <p></p>
    </div>
  </div>
</template>
<script setup>
import useWatermarkBg from '@/components/Watermark/useWatermarkBg'
import {defineProps, onMounted, onUnmounted, ref, watchEffect} from "vue";

const props = defineProps({
  text: {
    type: String,
    required: true,
    default: 'watermark'
  },
  fontSize: {
    type: Number,
    default: 40
  },
  gap: {
    type: Number,
    default: 20
  }
})
const parentRef = ref()
const bg = useWatermarkBg(props)
let div
const flag = ref(0)
let ob
watchEffect(() => {
  flag.value
  if (!parentRef.value) {
    return
  }
  if (div) {
    div.remove()
  }
  const {base64, size, styleSize} = bg.value
  div = document.createElement('div')
  div.style.backgroundImage = `url(${base64})`
  div.style.backgroundSize = `${styleSize}px ${styleSize}px`
  div.style.backgroundRepeat = 'repeat'
  div.style.width = '100%'
  div.style.height = '100%'
  div.style.marginTop = "200px"
  div.style.zIndex = '9'
  div.style.position = 'absolute'
  div.style.inset = 0
  parentRef.value.appendChild(div)
})

//监控页面
onMounted(() => {
  const ob = new MutationObserver((records) => {
    for (const record of records) {
      //监控删除
      for (const dom of record.removedNodes) {
        if (dom === div) {
          flag.value++
          return
        }
      }
      //监控修改
      if (record.target === div) {
        flag.value++
        return
      }
    }
  })
  ob.observe(parentRef.value, {
    childList: true, //监听元素内容
    subtree: true, //整个
    attributes: true //本身属性是否发生变化
  })
})
onUnmounted(() => {
  ob && ob.disconnect()
  div = null
})
</script>
<style lang="scss" scoped>

.con {
  width: 500px;
  height: 400px;
}

</style>